//require Model
const _ = require('lodash');
const mongoose = require('mongoose');
require('../model/verify.model');
const verifyModel = mongoose.model('Verify');

module.exports = {
    addVerify : addVerify,
    getVerifyById : getVerifyById,
    getVerifyByMid : getVerifyByMid,
    getAllVerify : getAllVerify,
    updateVerify : updateVerify
}

function addVerify(merchant, callback) {
    if(_.isEmpty(merchant)){
       callback(new Error("merchant is empty."), null); 
    }else{
        merchant.mid = merchant._id;
        getVerifyByMid(merchant.mid, function(err, doc){
            if(err) callback(err, null);
            if(doc){
                merchant._id = doc._id;
                merchant.state = 0;
                merchant.block = 0;
                merchant.submitTime = doc.submitTime;
                merchant.verifyTime = null;
                merchant.msg = null;
                verifyModel.updateOne({_id:merchant._id}, {$set: merchant}, function(err,result){
                    callback(err,result);
                });
            }else{
                verifyModel.create(merchant, function(err, result){
                    callback(err, result);
                });
            }
        });
        
    }
}

function getVerifyById(id, callback) {
    if(_.isEmpty(id)){
       callback(new Error("id is empty."), null); 
    }else{
        verifyModel.findOne({"_id":id},{__v:0}, function(err, doc){
            if(doc == null){
                callback(err, null); 
            }else{
                callback(err, doc);
            }
        });
    }
}

function getVerifyByMid(mid, callback) {
    if(_.isEmpty(mid)){
       callback(new Error("mid is empty."), null); 
    }else{
        verifyModel.findOne({"mid":mid},{__v:0}, function(err, doc){
            if(doc == null){
                callback(err, null); 
            }else{
                callback(err, doc);
            }
        });
    }
}

function getAllVerify(state, block, callback) {
    if(_.isEmpty(state) || _.isEmpty(block)){
       callback(new Error("state or block is empty."), null); 
    }else{
        var query = {};
        if(_.isEqual(block,"2")){
            query.state = state;
        }else{
            query.state = state;
            query.block = block;
        }
        verifyModel.find(query,{__v:0}, function(err, docs){
            if(docs == null){
                callback(err, null); 
            }else{
                callback(err, docs);
            }
        });
    }
}

function updateVerify(v, callback) {
    if(_.isEmpty(v)){
       callback(new Error("new verify is empty."), null); 
    }else{
        verifyModel.update({"mid": v.mid}, {$set: v}, function(err, docs){
            if(docs == null){
                callback(err, null); 
            }else{
                callback(err, docs);
            }
        });
    }
}